<template>
<div>
  <form action="#" @submit.prevent :class="scrollClass?'search_con_fixed':'search_con'">
    <i class="iconfont icon-sou searchIcon"></i>
    <input type="text" class="search_ipt" v-model="searchName" @keyup='search' placeholder="搜索">
  </form>
  <div class="friend_list">
    <div class="initial_word">
      <p v-for="(letter, index) in letterList" :key="index">{{letter}}</p>
    </div>
    <ul class="friends">
      <li @click="shareCheck(index, friend.friendId)" v-for="(friend, index) in friendList" :key="index">
        <div class="friend_check">
          <svg v-show="friend.isChecked" class="icon check_icon" aria-hidden="true">
            <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-zhaopianxuanzhong-"></use>
          </svg>
          <em v-show="!friend.isChecked"></em>
        </div>
        <div class="friendImg">
          <img :src="friend.url">
        </div>
        <span v-if="friend.friendNote">{{friend.friendNote}}</span>
        <span v-else>{{friend.usrName}}</span>
      </li>
    </ul>
    <div class="friends_foot">
      <div class="check_friend left">
        <img :src="checkedFriend.url" v-for="(checkedFriend,index) in checkedFriends" :key="index" />
      </div>
      <div class="confirm_menu">
        <span @click="cancel">取消</span>
        <span class="confirm_sure" @click="submit">确定({{checkedNum}})</span>
      </div>
    </div>
  </div>
  <!-- 分享成功 -->
  <share-success v-if="successShare" @clickBack="goBack" :noReward="noReward"></share-success>
  <!--奖励显示-->
  <reward-modal v-if="shareInfo" @close="hiddenShareInfo" :money="usrAmt" :state="padding"></reward-modal>
  <!-- shareInfo -->
</div>
</template>
<script>
import * as types from '../../vuex/types.js'
import ShareSuccess from '../coupon/shareList/success.vue'
import RewardModal from 'src/componentes/global/reward/index.vue'
import {
  mapGetters,
  mapState
} from 'vuex'
import {
  Toast
} from 'mint-ui'
import getData from '../../service/getData.js'
import {
  shareMyCoupon,
  searchFriend
} from '../../service/getData3.js'

export default {
  components: {
    ShareSuccess,
    RewardModal
  },
  data: function() {
    return {
      friendList: [],
      checkState: false,
      //        letterList: ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','W','X','Y','Z'],
      letterList: [],
      currentPage: 1,
      checkedFriends: [],
      searchName: '',
      successShare: false,
      scrollClass: false,
      shareInfo: false,
      usrAmt: 0,
      noReward: false,
      padding: false,
    }
  },
  beforeRouteLeave(to, from, next) {
    window.removeEventListener('scroll', this.handleScroll);

    next()
  },
  created: function() {
    window.addEventListener('scroll', this.handleScroll);
    let me = this;
    getData.myFriends({
      method: "post"
    }, me.userInfo.usrId).then(function(rep) {
      if (rep.respCode == '00') {
        //console.log(rep)
        let data = rep.content.friends;
        data.forEach(item => {
          item.isChecked = false
        })
        me.friendList = data
      }
    });
  },
  computed: {
    ...mapGetters(['coupon']),
    ...mapState({
      userInfo: state => state.user.userInfo
    }),
    checkedNum: function() {
      let len = this.checkedFriends.length
      return len
    }
  },
  methods: {
    handleScroll() {
      var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      if (scrollTop >= 40) {
        this.scrollClass = true;
      } else {
        this.scrollClass = false;
      }

    },
    goBack: function() {
      let type = this.$route.params.type
      //type  0:卡包  1：群友券
      if (type === '0') {
        window.history.go(-1);
        // this.$router.push({
        //   path: '/cardList'
        // })
      } else if (type === '1') {
        window.history.go(-2);
        // this.$router.push({
        //   path: '/friends'
        // })
      }
    },
    search: function() {
      searchFriend({
        usrId: this.userInfo.usrId,
        friendName: this.searchName,
      }).then(res => {
        if (res.respCode == '00') {
          let data = res.content.friends;
          data.forEach(item => {
            item.isChecked = false
          })
          this.friendList = data
        }
      })
    },
    cancel: function() {
    window.history.go(-1)
//    this.checkedFriends = []
//    this.friendList.forEach(friend => {
//      friend.isChecked = false
//    })
    },
    submit: function() {
      let friLen = this.checkedFriends.length
      if (friLen > 0) {
        let shareId = []
        this.checkedFriends.forEach(friItem => {
          shareId.push(friItem.friendId)
        })
        shareMyCoupon({
          usrId: this.userInfo.usrId,
          couponId: this.coupon.couponId,
          mchtId: this.coupon.mchtId,
          num: this.checkedFriends.length,
          shareId
        }).then(res => {
          if (res.respCode === '00') {
            console.log(res)
            this.usrAmt = res.content.usrAmt;
            if (!res.content.usrAmt) {
              if (res.content.verFlag == '1' || res.content.verFlag == '0') { //有奖励金机制
                if (res.content.shareProp == 0) {
                  this.noReward = false; //分享比例是零，无提示语
                } else {
                  this.noReward = true; //往上级分享或者分享次数达到层级限制，给提示没有奖励金
                }
              } else { //无奖励机制
                this.noReward = false;
              }
              this.successShare = true;
            }
            if (res.content.usrAmt == 0) { //奖励金是零
              if (res.content.verFlag == '1' || res.content.verFlag == '0') { //有奖励金机制
                if (res.content.shareProp == 0) {
                  this.noReward = false; //分享比例是零，无提示语
                } else {
                  this.noReward = true; //往上级分享或者分享次数达到层级限制，给提示没有奖励金
                }
              } else { //无奖励机制
                this.noReward = false;
              }
              this.successShare = true //分享成功
            } else { //奖励金不为零
              if (res.content.ifHasShareAmt) {
                // Toast({message: '分享成功！'})
                if (res.content.verFlag == '0') { //核销后给奖励，添加提示语（待入账）
                  this.padding = true;
                } else if (res.content.verFlag == '1') {
                  this.padding = false;
                }
                this.shareInfo = true; //奖励提醒
              }
            }
            this.$store.commit('shareCoup')
          } else {
            Toast({
              message: res.errorInfo
            })
          }
        })
      } else {
        Toast({
          message: '请选择您要分享的券友！'
        })
      }
    },
    hiddenShareInfo() {
      this.shareInfo = false;
      let type = this.$route.params.type
      //type  0:卡包  1：群友券
      if (type === '0') {
        window.history.go(-1);
      } else if (type === '1') {
        window.history.go(-2);
      }
    },
    shareCheck: function(index, friendId) {
      let friLen = this.checkedFriends.length
//    let couLen = this.coupon.num
      let couLen = 1
      if (friLen <= couLen) {
        if (friLen < couLen) {
          this.friendList[index].isChecked = !this.friendList[index].isChecked
        }
        let isChecked = this.friendList[index].isChecked
        if (isChecked && friLen !== couLen) {
          this.checkedFriends.push(this.friendList[index])
        } else if (this.checkedFriends.length > 0) {
          let key // 存下标，被点击的券友与被存储的券友相同时
          this.checkedFriends.forEach(function(friend, id) {
            if (friend.friendId === friendId) {
              key = id
            }
          })
         
          if (key !== undefined) {
            this.friendList[index].isChecked = false
            this.checkedFriends.splice(key, 1)
          } else {
            Toast({
              message: '一次只能分享一个人！'
            })
          }
        }
      } else {
        Toast({
          message: '分享人数超过了您的电子券数量！'
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.friendImg {
    margin-left: 0.667rem;
}
.searchIcon {
    font-size: 2rem;
}
.friend_list > .friends > li em {
    display: block;
    width: 1.25rem;
    height: 1.25rem;
    margin-top: 1.38rem;
    box-sizing: border-box;
    border-radius: 50%;
    background-color: #f6f6f6;
    border: 1px solid #ddddde;
}
.friends {
    margin-bottom: 2.1rem;
}

.friend_list .check_icon {
    margin: 1.3rem 0 0;
    width: 1.44rem;
    height: 1.44rem;
    font-size: 1.4rem;
}

.friend_list .friend_check {
    float: left;
    width: 2.1rem;
    padding-left: 1rem;
}

.friends_foot {
    height: 3rem;
    line-height: 3rem;
    background-color: #fff;
    border-top: 1px solid #f0f0f0;
    border-bottom: 1px solid #6d92ca;
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
}

.confirm_menu {
    float: right;
    color: #ec4e8a;
    font-size: 1rem;
    text-align: center;
}

.confirm_menu span {
    float: left;
    width: 5rem;
}

.confirm_menu .confirm_sure {
    width: 6rem;
    color: #fff;
    background-color: #ec4e8a;
}

.check_friend {
    /*display: -webkit-flex;
        display: flex;
        align-items: center;*/
    width: calc(100% - 12rem);
    height: 3rem;

    margin-left: 0.667rem;
    overflow: hidden;
}

.check_friend img {
    float: left;
    width: 2.2rem;
    height: 2.2rem;
    margin: 0.45rem 0.5rem 0 0;
}
.search_con_fixed {
    padding: 0 0.667rem;
    height: 4rem;
    border-bottom: 1px solid #f0f0f0;
    background: #fff;
    line-height: 4rem;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 9;
}
</style>
